package com.cloud.tool.config;

import com.cloud.tool.exception.ToolException;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.ClusterServersConfig;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Classname MyRedissonConfig
 * @Date 2021/6/4 14:04
 * @Author WangZY
 * @Description Redisson配置
 */
@Configuration
public class MyRedissonConfig {
    @Autowired
    private ConfigurableEnvironment config;

    /**
     * 对 Redisson 的使用都是通过 RedissonClient 对象
     */
    @Bean(destroyMethod = "shutdown") // 服务停止后调用 shutdown 方法。
    public RedissonClient redisson() {
        String redisHost = config.getProperty("spring.redis.host");
        String redisPort = config.getProperty("spring.redis.port");
        String cluster = config.getProperty("spring.redis.cluster.nodes");
        String redisPassword = config.getProperty("spring.redis.password");
        // 1.创建配置
        Config config = new Config();
        //使用String序列化时会出现RBucket<Integer>转换异常
//        config.setCodec(new StringCodec());
        if (StringUtils.isEmpty(redisHost) || StringUtils.isEmpty(redisPort)) {
            if (StringUtils.isEmpty(cluster)) {
                throw new ToolException("spring.redis.host及port或spring.redis.cluster" +
                        ".nodes必填，否则不可使用RedisTool以及Redisson");
            } else {
                // 集群模式
                String[] split = cluster.split(",");
                List<String> servers = new ArrayList<>();
                for (String s : split) {
                    servers.add("redis://" + s);
                }
                ClusterServersConfig clusterServers = config.useClusterServers();
                clusterServers.addNodeAddress(servers.toArray(new String[split.length]));
                if (!StringUtils.isEmpty(redisPassword)) {
                    clusterServers.setPassword(redisPassword);
                }
                //修改命令超时时间为40s，默认3s
                clusterServers.setTimeout(40000);
                //修改连接超时时间为30s，默认10s
                clusterServers.setConnectTimeout(50000);
            }
        } else {
            // 单机模式
            SingleServerConfig singleServer = config.useSingleServer();
            singleServer.setAddress("redis://" + redisHost + ":" + redisPort);
            if (!StringUtils.isEmpty(redisPassword)) {
                singleServer.setPassword(redisPassword);
            }
            singleServer.setTimeout(40000);
            singleServer.setConnectTimeout(30000);
        }
        return Redisson.create(config);
    }
}
